﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net; 
using System.Text;
using System.Text.RegularExpressions;
using System.Timers;
using System.Windows.Forms;
using System.Xml.Linq;
using Deerchao.Utility;
using LeoShi.Soft.OpenSinaAPI;
using Shoping.Monitor.Helper;
using Shoping.Monitor.OAuth2;
using Timer = System.Timers.Timer;

namespace Shoping.Monitor
{
    public partial class MainForm : Form
    {

        private Dictionary<DataGridViewRow, Timer> _workers;

        private DataGridViewRow _row;
        private const string Redirect_Uri = "http://127.0.0.1/oauth.html";


        public MainForm()
        {
            InitializeComponent();
            _workers = new Dictionary<DataGridViewRow, Timer>();
            cbMatch.SelectedItem = "匹配有货";
        }
         
         

        private void btnStart_Click(object sender, EventArgs e)
        { 
            btnStop.Enabled = true;
            btnStart.Enabled = false;

            foreach (var worker in _workers)
            {
                worker.Value.Start();
            } 
        }

        private void btnStop_Click(object sender, EventArgs e)
        {  
            btnStop.Enabled = false;
            btnStart.Enabled = true;

            foreach (var worker in _workers)
            {
                worker.Value.Stop();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (null != _row)
            {
                var row = _row;
                var task = row.Tag as Task;
                row.Cells["Product"].Value = txtProduct.Text;  
                row.Cells["Site"].Value = txtUrl.Text; 

                task.ProductName = txtProduct.Text;
                task.MatchType = cbMatch.Text == "匹配有货" ? MatchType.匹配有货 : MatchType.匹配无货;
                task.Url = txtUrl.Text;
                task.Regex = txtRegex.Text;
                task.FilterHtml = ckFilteHtml.Checked;
            }
            else
            {

                var i = gvList.Rows.Add();
                var row = gvList.Rows[i];
                var task = new Task
                               {
                                   ProductName = txtProduct.Text,
                                   MatchType = cbMatch.Text == "匹配有货" ? MatchType.匹配有货 : MatchType.匹配无货,
                                   Url = txtUrl.Text,
                                   Regex = txtRegex.Text,
                                   FilterHtml = ckFilteHtml.Checked
                               };

                row.Tag = task;
                row.Cells["Product"].Value = txtProduct.Text; 
                row.Cells["Site"].Value = txtUrl.Text; 
                var timer = new Timer
                    {
                        Interval = int.Parse(txtInterval.Text)*1000
                    };
                timer.Elapsed += timer_Elapsed;
                _workers.Add(row,timer);
                if (!btnStart.Enabled)
                {
                    timer.Start();
                } 
            }


        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {

                var timer = sender as Timer;
                var worker = _workers.FirstOrDefault(x => x.Value == timer);
                var row = worker.Key;
                var data = row.Tag as Task;
                var client = new HttpClient(data.Url); 
                var content = client.GetString();
                if (data.FilterHtml)
                {
                    content = new HtmlToText().Convert(content); 
                }

                var regex = data.Regex;
                var isMatch = data.MatchType == MatchType.匹配有货;
                var disable = Regex.IsMatch(content, regex) && isMatch;
                var newValue = disable ? "有货" : "无货";
                var oldValue = data.Disable;
                if (oldValue != newValue)
                {
                    var icon = disable ? ToolTipIcon.Info : ToolTipIcon.Error;
                    var title = data.ProductName + newValue;
                    var text = data.Url;
                    notify.ShowBalloonTip(15*1000, title, text, icon);
                    notify.BalloonTipText = text;


                    if (cbSinaSend.Enabled && cbSinaSend.Checked && newValue.Contains("有货"))
                    {
                        try
                        {
                            var imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
                                                         DateTime.Now.ToString("yyyyMMddHHmmss")+Guid.NewGuid().ToString() + ".jpg");
                            
                            //if (UrlToImage.Invoke(this,data.Url, imagePath))
                            //{
                            //    var postUrl = "https://upload.api.weibo.com/2/statuses/upload.json";
                            //    var httpClient = new HttpClient(postUrl);
                            //    httpClient.PostingData.Add("access_token", lbSinaUserName.Tag.ToString());
                            //    httpClient.PostingData.Add("status", title + "\r\n" + text);
                            //    httpClient.Files.Add(new HttpUploadingFile(imagePath, "pic"));
                            //    httpClient.GetString();

                            //}
                            //else
                            //{
                                var postUrl = "https://api.weibo.com/2/statuses/update.json";
                                var httpClient = new HttpClient(postUrl);
                                httpClient.PostingData.Add("access_token", lbSinaUserName.Tag.ToString());
                                httpClient.PostingData.Add("status", title + "\r\n" + text);
                                httpClient.GetString();

                            //}

                            this.Invoke(new Action(() =>
                                {
                                    txtOutput.Text += string.Format("{0} 推送消息[{1}到新浪微博\r\n",
                                                                    DateTime.Now.ToString(),
                                                                    title);

                                }));


                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString(), "推送到新浪微博失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }



                }

                row.Cells["Disable"].Value = newValue;
                data.Disable = newValue;
                row.Cells["Date"].Value = DateTime.Now;
                data.Date = DateTime.Now.ToString();


            }
            catch (Exception)
            {

            }

        }
         

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (null != _row)
            {
                var timer =  _workers[_row]; 
                if (!btnStart.Enabled)
                {
                    timer.Stop();
                } 
                _workers.Remove(_row);
                gvList.Rows.Remove(_row);
                _row = null;
                btnDelete.Enabled = false;
            }
        }

        private void gvList_SelectionChanged(object sender, EventArgs e)
        {
            if (gvList.SelectedRows.Count > 0)
            {
                var row = gvList.SelectedRows[0];
                _row = row;
                btnDelete.Enabled = true;
                var data = row.Tag as Task;
                txtProduct.Text = data.ProductName;
                txtUrl.Text = data.Url;
                txtRegex.Text = data.Regex;
                cbMatch.SelectedItem = data.MatchType.ToString();
                ckFilteHtml.Checked = data.FilterHtml;
            }
            else
            {
                _row = null;
                btnDelete.Enabled = false;
                txtProduct.Text = "";
                txtUrl.Text = "";
                txtRegex.Text = "";
                cbMatch.SelectedItem = MatchType.匹配有货.ToString();
                ckFilteHtml.Checked = true;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            var paht = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data.xml");
            if (File.Exists(paht))
            {
                var doc = XDocument.Load(paht);
                foreach (var item in doc.Element("data").Elements("item"))
                {
                    var i = gvList.Rows.Add();
                    var row = gvList.Rows[i];
                    row.Cells["Product"].Value = item.Element("Product").Value;
                    row.Cells["Site"].Value = item.Element("Site").Value;
                    row.Cells["Disable"].Value = item.Element("Disable").Value;
                    row.Cells["Date"].Value = item.Element("Date").Value;
                    row.Tag = new Task
                                  {
                                      Regex = item.Element("Regex").Value,
                                      Date = item.Element("Date").Value,
                                      Disable = item.Element("Disable").Value,
                                      FilterHtml = item.Element("FilterHtml").Value == "true",
                                      MatchType =
                                          item.Element("MatchType").Value == "匹配有货" ? MatchType.匹配有货 : MatchType.匹配无货,
                                      ProductName = item.Element("Product").Value,
                                      Url = item.Element("Site").Value
                                  }; 
                    var timer = new Timer
                    {
                        Interval = int.Parse(txtInterval.Text) * 1000
                    };
                    timer.Elapsed += timer_Elapsed;
                    _workers.Add(row, timer);
                    if (!btnStart.Enabled)
                    {
                        timer.Start();
                    } 
                }
            }

            var sinaOauthDataPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "sinaoauth2.xml");
            if (File.Exists(sinaOauthDataPath))
            {
                var data = XDocument.Load(sinaOauthDataPath); 

                var token = new AccessToken { 
                    access_token = data.Element("data").Element("access_token").Value,
                    uid = data.Element("data").Element("uid").Value 
                };
                var user = new UserShow
                               {
                                   id = data.Element("data").Element("uid").Value ,
                                   screen_name = data.Element("data").Element("screen_name").Value 

                               }; 
                lbSinaUserName.Tag = token.access_token; 
                lbSinaUserName.Text = user.screen_name;
                lbSinaUserName.ForeColor = Color.Green;
                btnLoginSina.Text = "注销"; 
                cbSinaSend.Enabled = true;
            }


        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            var paht = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data.xml");
            var data = new XElement("data");
            var doc = new XDocument(data);

            foreach (DataGridViewRow row in gvList.Rows)
            {
                var task = row.Tag as Task;
                data.Add(new XElement("item",
                                        new XElement("Product", task.ProductName),
                                      new XElement("Site", task.Url),
                                      new XElement("Regex", task.Regex),
                                      new XElement("MatchType", task.MatchType),
                                      new XElement("Disable", task.Disable),
                                      new XElement("Date", task.Date),
                                      new XElement("FilterHtml", task.FilterHtml)));
            }
            doc.Save(paht);
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮 
            if (WindowState == FormWindowState.Minimized)
            { 
                //隐藏任务栏区图标 
                this.ShowInTaskbar = false; 
            }
        }

        private void notify_DoubleClick(object sender, EventArgs e)
        {
            //判断是否已经最小化于托盘 
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示 
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点 
                this.Activate();
                //任务栏区显示图标 
                this.ShowInTaskbar = true; 
            }
        }

        private void notify_BalloonTipClicked(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(notify.BalloonTipText);
            }
            catch (System.ComponentModel.Win32Exception noBrowser)
            {
                if (noBrowser.ErrorCode == -2147467259)
                    MessageBox.Show(noBrowser.Message);
            }
            catch (System.Exception other)
            {
                MessageBox.Show(other.Message);
            }
        }
         

        private void button1_Click(object sender, EventArgs e)
        {


            //var client = new HttpClient(textBox1.Text);
            //var content = client.GetString();
            //content = new HtmlToText().Convert(content);
            //var paht = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "log.txt");
            //File.WriteAllText(paht, content);
            //MessageBox.Show("ok"); 

           
        }

        private void btnLoginSina_Click(object sender, EventArgs e)
        {
            var url = "https://api.weibo.com/oauth2/authorize?client_id=" + GlobalInfo.appKey +
                      "&response_type=code&redirect_uri=" + System.Web.HttpUtility.UrlEncode(Redirect_Uri);
            var login = new Login(url);
            var result = login.ShowDialog();
            if (result == DialogResult.OK)
            {

                try
                {
                    string postString = "client_id=" + GlobalInfo.appKey +
                                        "&client_secret=" + GlobalInfo.appSecret +
                                        "&grant_type=authorization_code&redirect_uri=" +
                                        System.Web.HttpUtility.UrlEncode(Redirect_Uri) + "&code=" + login.Code;
                    byte[] postData = Encoding.UTF8.GetBytes(postString);
                    string toUrl = "https://api.weibo.com/oauth2/access_token";
                    var webClient = new WebClient();
                    webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    byte[] responseData = webClient.UploadData(toUrl, "POST", postData); //得到返回字符流  
                    string tokenResult = Encoding.UTF8.GetString(responseData); //解码


                    var token = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessToken>(tokenResult);
                    lbSinaUserName.Tag = token.access_token;
                    var userUrl = "https://api.weibo.com/2/users/show.json?access_token=" + token.access_token + "&uid=" +
                                  token.uid;
                    webClient.Encoding = Encoding.UTF8;
                    var userString = webClient.DownloadString(userUrl);
                    var user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserShow>(userString);
                    lbSinaUserName.Text = user.screen_name;
                    lbSinaUserName.ForeColor = Color.Green;
                    btnLoginSina.Text = "注销";
                    cbSinaSend.Enabled = true;

                    var paht = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "sinaoauth2.xml");

                    var doc = new XDocument(new XElement("data", new XElement("access_token", token.access_token),
                                              new XElement("uid", token.uid),
                                              new XElement("screen_name", user.screen_name)));
                     
                    doc.Save(paht);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}
